/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.rukopisy.tools.cli.imageLinks;

import cz.mzk.kramerius.commons.DatastreamId;
import cz.mzk.kramerius.commons.Dom4jUtils;
import cz.mzk.kramerius.commons.Namespaces;
import cz.mzk.kramerius.fedoraaccess.FedoraConnector;
import cz.mzk.kramerius.fedoraaccess.metadataUpdate.datastream.InlineXmlDatastreamUpdater;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.QName;
import org.dom4j.XPath;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
public class RelsExtTilesAdder extends InlineXmlDatastreamUpdater {

    private static final XPath descriptionXpath = Dom4jUtils.createXPath("//rdf:RDF/rdf:Description");
    private static final XPath tilesXpath = Dom4jUtils.createXPath("kramerius:tiles-url");
    private final String tilesUrl;

    public RelsExtTilesAdder(FedoraConnector con, String tilesUrl) {
        super(con, DatastreamId.RELS_EXT);
        this.tilesUrl = tilesUrl;
    }

    @Override
    public Document updateDatastreamDoc(Document originalDs) {
        Element description = (Element) descriptionXpath.selectSingleNode(originalDs);
        removeTilesUrlElementsIfPresent(description);
        Element tilesUrlEl = description.addElement(new QName("tiles-url", Namespaces.kramerius));
        tilesUrlEl.addText(tilesUrl);
        return originalDs;
    }

    private void removeTilesUrlElementsIfPresent(Element description) {
        List<Element> tilesUlrElements = tilesXpath.selectNodes(description);
        for (Element tilesUrlEl : tilesUlrElements) {
            tilesUrlEl.detach();
        }
    }
}
